package io.renren.modules.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.web.dao.CourseDao;
import io.renren.modules.web.entity.CourseEntity;
import io.renren.modules.web.service.CategoryService;
import io.renren.modules.web.service.CourseService;
import io.renren.modules.web.vo.CategoryLayerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("courseService")
public class CourseServiceImpl extends ServiceImpl<CourseDao, CourseEntity> implements CourseService {
    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<CourseEntity> wrapper = new QueryWrapper<CourseEntity>().orderByDesc("update_time");
        if (StringUtils.hasLength(key)) {
            wrapper.like("name", key).or().like("teacher", key);
        }

        IPage<CourseEntity> page = this.page(
                new Query<CourseEntity>().getPage(params),
                wrapper
        );

        List<CourseEntity> records = page.getRecords();
        List<CourseEntity> courseVoList = records.stream().peek(courseEntity -> {
            Long categoryId = courseEntity.getCategoryId();
            CategoryLayerVo categoryLayer = categoryService.getCategoryLayer(categoryId);
            List<String> categoryNameLayer = categoryLayer.getCategoryNameLayer();
            String categoryName = String.join("/", categoryNameLayer);
            courseEntity.setCategoryName(categoryName);
        }).collect(Collectors.toList());
        page.setRecords(courseVoList);
        return new PageUtils(page);
    }

    @Override
    public List<CourseEntity> getCourseListByCategoryId(Long categoryId) {
        return baseMapper.selectList(new QueryWrapper<CourseEntity>().eq("category_id", categoryId));
    }

}